package com.yzkj.cpjxc.business.controller;

import com.yzkj.cpjxc.business.framework.common.*;
import com.yzkj.cpjxc.business.framework.utils.CollectionHelp;
import com.yzkj.cpjxc.business.framework.utils.StringHelp;
import com.yzkj.cpjxc.business.domain.ZTreeComm;
import com.yzkj.cpjxc.business.domain.SysAuthority;
import com.yzkj.cpjxc.business.domain.SysAuthorityQueryVo;
import com.yzkj.cpjxc.business.domain.SysAuthorityShowVo;
import com.yzkj.cpjxc.business.service.SysAuthorityService;
import com.yzkj.cpjxc.business.service.SysRoleService;
import com.yzkj.cpjxc.business.service.SysUserService;
import com.yzkj.cpjxc.business.system.interceptor.DoLog;
import com.yzkj.cpjxc.business.system.interceptor.Permission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 系统权限控制类
 */
@Controller
@RequestMapping("/sysAuthority")
public class SysAuthorityController extends BaseController {

	@Autowired
	private SysAuthorityService sysAuthorityService;
	
	@Autowired
	private SysRoleService sysRoleService;

	@Resource
	private SysUserService sysUserService;

	@RequestMapping("/list") 
	@DoLog(cnContent = "去到权限列表信息", value = false)
	@Permission(name = "sysAuthority.view")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response, SysAuthority sysAuthority) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysAuthority/mgr").addAllObjects(modelMap);
	}

	@RequestMapping("/ajaxPage") 
	@DoLog(cnContent = "权限列表ajax分页", value = false) 
	@Permission(name = "sysAuthority.view")
	public String ajaxPage(HttpServletRequest request, HttpServletResponse response, SysAuthority sysAuthority) throws Exception {
		try {
			Pager<SysAuthorityShowVo> p = new Pager<SysAuthorityShowVo>();
			p.setCurrentPage(this.getCurrentPage(request));
			// 1、获取分页数据
			Pager<SysAuthorityShowVo> pager = sysAuthorityService.search(p, sysAuthority);
			this.genPageJson(response, pager);
			return null;
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/toAdd") 
	@DoLog(cnContent = "去到添加权限页面", value = false) 
	@Permission(name = "sysAuthority.add")
	public ModelAndView toAdd(HttpServletRequest request, HttpServletResponse response, SysAuthorityQueryVo queryVo) throws Exception {
		//1、组装数据，权限类型，状态下拉框
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		SysAuthority parentSysAuthority = sysAuthorityService.getById(queryVo.getParentId());
		modelMap.put("parentSysAuthority", parentSysAuthority);
		modelMap.put("authTypeMap", ConstantParam.authTypeMap);
		modelMap.put("statusMap", ConstantParam.statusMap);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysAuthority/add").addAllObjects(modelMap);
	}

	@RequestMapping("/add") 
	@DoLog(cnContent = "添加权限", operationAction = "C") 
	@Permission(name = "sysAuthority.add")
	public void add(HttpServletRequest request, HttpServletResponse response, SysAuthority sysAuthority) throws Exception {
		try {
			
			//过滤指定非法字符
			StringHelp.replaceFilteringChars(SysAuthority.class, sysAuthority);
			
			BusinessMap bm = sysAuthorityService.create(sysAuthority);
			this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
			if (!bm.getIsSucc()) {
				return;
			}

		} catch (Exception e) {
			this.logException(e);
			this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/toEdit") 
	@DoLog(cnContent = "去到编辑权限页面", value = false) 
	@Permission(name = "sysAuthority.edit")
	public ModelAndView toEdit(HttpServletRequest request, HttpServletResponse response, SysAuthority sysAuthority) throws Exception {
		//1、根据id获取数据
		SysAuthority result = sysAuthorityService.getById(sysAuthority.getAuthorityId());
		//2、组装数据
		SysAuthorityShowVo sysAuthorityShowVo = new SysAuthorityShowVo();
		BeanUtils.copyProperties(result, sysAuthorityShowVo, new String[] {
				"parentSysAuthority", "sysAuthoritys"
		});
		SysAuthority parentSysAuthority = sysAuthorityService.getById(result.getParentId());
		sysAuthorityShowVo.setParentAuthorityName(parentSysAuthority == null ? "" : parentSysAuthority.getAuthorityName());
		//3、
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("authTypeMap", ConstantParam.authTypeMap);
		modelMap.put("statusMap", ConstantParam.statusMap);
		modelMap.put("sysAuthorityShowVo", sysAuthorityShowVo);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysAuthority/edit").addAllObjects(modelMap);
	}

	@RequestMapping("/edit") 
	@DoLog(cnContent = "编辑权限", operationAction = "U") 
	@Permission(name = "sysAuthority.edit")
	public void edit(HttpServletRequest request, HttpServletResponse response, SysAuthority sysAuthority) throws Exception {
		try {
			
			//过滤指定非法字符
			StringHelp.replaceFilteringChars(SysAuthority.class, sysAuthority);
			
			SysAuthority result = sysAuthorityService.getById(sysAuthority.getAuthorityId());
			SysAuthority sau = new SysAuthority();
			sau.setLevelCode(result.getLevelCode());
			
			BusinessMap bm = sysAuthorityService.edit(sysAuthority);
			
			if (bm.getIsSucc()) {
				
				//如果LevelCode有变化   更改子权限LevelCode
				if (!StringUtils.equals(result.getLevelCode(), sysAuthority.getLevelCode())) {
					//查询源子权限列表
					SysAuthorityQueryVo wuq = new SysAuthorityQueryVo();
					wuq.setLevelCode(result.getLevelCode()+"-");
					List<SysAuthority> childlist = sysAuthorityService.queryByCondition(wuq);
					SysAuthority temp = null;
					for(SysAuthority sa:childlist){
						temp = new SysAuthority();
						BeanUtils.copyProperties(sa, temp, new String[] {
								"parentSysAuthority", "webAuthoritys"
						});
						sysAuthorityService.edit(temp);
					}
				}

				//如果启用 停用状态有改变 则改变子类同一状态
				String status1 = result.getStatus();
				String status2 = sysAuthority.getStatus();

				if (!status1.equals(status2)) {

					if (Constants.STATUS_ACTIVE.equals(status1)) {
						//停用该节点的同时会将其下辖节点也一并停用
						sau.setStatus(Constants.STATUS_INACTIVE);
						sysAuthorityService.editChildStatusByLevelCode(sau);
					} else {
						//启用该节点的同时会将其父节点也一并启用
						sau.setStatus(Constants.STATUS_ACTIVE);
						String levelCode = sau.getLevelCode();
						if (levelCode != null) {
							String[] lcs = levelCode.split("-");
							 sysAuthorityService.editChildStatusId(Arrays.asList(lcs));
						}
					}
				}
			}
			
			this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
			if (!bm.getIsSucc()) {
				return;
			}

		} catch (Exception e) {
			this.logException(e);
			this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/view") 
	@DoLog(cnContent = "查看权限信息", value = false) 
	@Permission(name = "sysAuthority.view")
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response, SysAuthority sysAuthority) throws Exception {
		//1、根据id获取权限
		SysAuthority result = sysAuthorityService.getById(sysAuthority.getAuthorityId());
		//2、组装数据
		SysAuthorityShowVo showVo = new SysAuthorityShowVo();
		BeanUtils.copyProperties(result, showVo, new String[] {
				"parentSysAuthority", "sysAuthoritys"
		});
		//2.1、获取权限集合中的父节点名称
		SysAuthority parentSysAuthority = result.getParentSysAuthority();
		showVo.setParentAuthorityName(parentSysAuthority == null ? "" : parentSysAuthority.getAuthorityName());
		return new ModelAndView("sysMgr/securityMgr/sysAuthority/view").addObject("sysAuthorityShowVo", showVo).addObject("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
	}

	@RequestMapping("/delete") 
	@DoLog(cnContent = "删除权限信息", operationAction = "D") 
	@Permission(name = "sysAuthority.delete")
	public void delete(HttpServletRequest request, HttpServletResponse response, SysAuthority sysAuthority) throws Exception {
		try {
			//1、获取权限详细
			SysAuthority result = sysAuthorityService.getById(sysAuthority.getAuthorityId());
			//2、判断父节点，如果父节点为空，则是顶级节点，不可删除
			if(StringUtils.isBlank(result.getParentId())){
				this.ajax(response, "无权限删除顶级权限节点!");
				return;
			}
			
			//如果当前节点存在子节点 ，则不允许删除
			if(sysAuthorityService.isHavaChilds(result.getLevelCode())){
				this.ajax(response, "该权限底下存在子数据权限，不能删除");
				return;
			}
			
			//物理删除
			boolean flag = sysAuthorityService.deleteByLevelCode(result.getLevelCode());
			this.ajax(response, flag ? Constants.SUCCESS : Constants.ERROR);
		} catch (Exception e) {
			this.logException(e);
			this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	// =======================================================================================================================================
	@RequestMapping("/authorityMenuTree") @DoLog(cnContent = "本系统权限树", value = false)
	public String authorityMenuTree(HttpServletRequest request, HttpServletResponse response, ZTreeComm comm, String initId) throws Exception {
		try {
			//初始树的时候,从本系统开始初始化
			SysAuthority sysAuthority = sysAuthorityService.getById(initId);
			String[] ids = sysAuthority.getLevelCode().split("-");
			List<ZTreeComm> list = sysAuthorityService.getAllChildByLevelCode(ids[0]);
			return this.ajax(response, list);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/authorityTree")
	@DoLog(cnContent = "权限树", value = false)
	public String authorityTree(HttpServletRequest request, HttpServletResponse response, ZTreeComm zTree) throws Exception {
		try {
			String roleId = zTree.getDiyParams();
			List<SysAuthority> saList = sysAuthorityService.getSysAuthoritysByRoleId(roleId);
			
			SysAuthorityQueryVo sVo = new SysAuthorityQueryVo();
			sVo.setStatus(Constants.STATUS_ACTIVE);
			
			List<SysAuthority> list = sysAuthorityService.queryByCondition(sVo);
			List<ZTreeComm> ztreeList = new ArrayList<ZTreeComm>();
			ZTreeComm ztreeComm = null;
			if (CollectionHelp.isNotBank(list)) {
				for (SysAuthority sa : list) {
					ztreeComm = new ZTreeComm();
					ztreeComm.setId(sa.getAuthorityId());
					ztreeComm.setpId(sa.getParentId());
					ztreeComm.setName(sa.getAuthorityName());
					ztreeComm.setSortNo(sa.getSortNo());
					ztreeComm.setChecked(saList.contains(sa) ? Constants.IS_TRUE : Constants.IS_FALSE);
					ztreeList.add(ztreeComm);
				}
			}

			return this.ajax(response, ztreeList);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/mgr")
	@DoLog(cnContent = "加载权限管理树", value = false)
	@Permission(name = "sysAuthority.view")
	public String mgr(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			List<ZTreeComm> ztreeList = new ArrayList<ZTreeComm>();
			
			List<SysAuthority> authList = sysAuthorityService.queryByCondition(new SysAuthorityQueryVo());
			if (CollectionHelp.isNotBank(authList)) {
				ZTreeComm ztreeComm = null;
				for (SysAuthority sa : authList) {
					ztreeComm = new ZTreeComm();
					ztreeComm.setId(sa.getAuthorityId());
					ztreeComm.setpId(sa.getParentId());
					ztreeComm.setName(sa.getAuthorityName());
					ztreeComm.setSortNo(sa.getSortNo());
					ztreeComm.setOpen(Constants.IS_FALSE);
					ztreeList.add(ztreeComm);
				}
			}

			// 转成json输出到浏览器展示
			return this.ajax(response, ztreeList);
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

}
